<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'form/gform_ctrl.class.php');

require_once('attachment_upload_form.class.php');
require_once('attachment_upload_form_view.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/settings/tcms_settings_attachments_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/attachment/tcms_attachment.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/attachment/tcms_attachment_upload.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_dbc.class.php');


class Attachment_Upload_Form_Ctrl extends GForm_Ctrl {
	private $attachment_settings;
	private $dbc;
	private $uploads_dir;
	private $attachment_id;

	function __construct($system_name, Vars_Manager $vm, TCMS_Settings_Attachments_DBC $attachment_settings, DB_Connection $dbc, $uploads_dir) {
		$this->attachment_settings = $attachment_settings;
		$this->dbc = $dbc;
		$this->uploads_dir = $uploads_dir;

		parent::__construct($system_name, $vm);
	}


	protected function create_form() {
		$form = new Attachment_Upload_Form($this->attachment_settings->get_max_size());

//		$form->generate_html();

		return $form;
	}


	protected function create_form_view() {
		$ret = new Attachment_Upload_Form_View($this->form);

		return $ret;
	}


	protected function on_good_submit() {
		$ret = true;

		$file_prop = $this->form->get_field_value('attachment');

		if (TCMS_Attachment::is_valid_extension($file_prop['name'], $this->attachment_settings->get_forbidden_extensions())) {
			$ci_id = $this->get_permanent_external_param('ci', true);
			try {
				$this->dbc->start_trans();
				$this->attachment_id = TCMS_Attachment_Upload::process_uploaded_file($this->dbc,
																					$file_prop,
																					$this->uploads_dir,
																					$this->attachment_settings,
																					$ci_id,
																					$this->get_permanent_external_param('user_id')
																					);
				$this->dbc->complete_trans();
			} catch (Exception $e) {
				$this->dbc->fail_trans();
				$this->dbc->complete_trans();
				throw $e;
			}
		} else {
			$ret = false;
			$this->export('forbidden_extensions', $this->attachment_settings->get_forbidden_extensions());
			$this->form->set_field_error('attachment', 'invalid_extension');
		}

		if (!$ret) { // cleaning uploaded file (this is (over)tidy. PHP will delete it automatically but only if not crashes by some reason (segfault for example))
			if (file_exists($file_prop['tmp_name'])) {
				unlink($file_prop['tmp_name']);
			}
		}

		return $ret;
	}


	protected function on_bad_submit() {
		$errors = $this->form->get_field_errors('attachment');

		$ci_id = $this->get_permanent_external_param('ci', true);
		if ($ci_id) {
			$this->export('ci_id', $ci_id);
		}
	}

}